import React, { Component } from 'react';
import { Button, Calendar, DatePicker, Radio, Row, Col, Tooltip, Spin } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { CONST_MODE_CALENDAR, CONST_MODE_LIST, CONST_DATE_FORMAT } from '@/constants';
import styles from '../index.less';

import List from './List';

const ButtonGroup = Button.Group;
const { MonthPicker } = DatePicker;
const CONST_PICKER_FORMAT = 'YYYY-MM';

export default class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            time: moment()
        }
        if (typeof props.onSelect === 'function') {
            props.onSelect(undefined, this.state.time.clone(), true);
        }
    }

    componentDidMount() {
        const { time } = this.state;
        const { currentUnit } = this.props;

        this.queryData(time, currentUnit);
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (!_.isEqual(this.props.currentUnit, nextProps.currentUnit) || !_.isEqual(this.props.refreshTime, nextProps.refreshTime) || !_.isEqual(this.state.time, nextState.time)) {
            const { time } = nextState;
            const { currentUnit } = nextProps;

            this.queryData(time, currentUnit);
        }

        return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState)
    }

    onDateChange = (time) => {
        this.setState({ time });
    }

    onRadioChange = (e) => {
        this.setState({ time: moment(e.target.value, CONST_PICKER_FORMAT) }, () => {
            const { data = {}, time } = this.state;

            if (typeof this.props.onSelect === 'function') {
                this.props.onSelect(undefined, time.clone(), true);
            }
        });
    }

    onButtonClick = (type) => {
        const { time } = this.state;
        let newTime = undefined;

        if (type === 'prev') {
            newTime = moment(time).add(-1, 'months');
        } else if (type === 'next') {
            newTime = moment(time).add(1, 'months');
        } else {
            newTime = moment();
        }

        this.setState({ time: newTime });
        if (typeof this.props.onSelect === 'function') {
            this.props.onSelect(undefined, newTime.clone(), true);
        }
    }

    onSelect = (time) => {
        const { data = {} } = this.state;

        if (time.format(CONST_PICKER_FORMAT) !== this.state.time.format(CONST_PICKER_FORMAT)) {
            this.setState({ time });
        }
        if (typeof this.props.onSelect === 'function') {
            this.props.onSelect(data[time.format(CONST_DATE_FORMAT)], time.clone());
        }
    }

    queryData = (time, unit = {}) => {
        const { dispatch, modularName } = this.props;

        if (time) {
            dispatch({
                type: `${modularName}/queryData`,
                payload: {
                    startDate: moment(time).startOf('month').format(CONST_DATE_FORMAT),
                    endDate: moment(time).endOf('month').format(CONST_DATE_FORMAT),
                    shift_unit: { id: unit.id },
                    callback: (data) => {
                        this.setState({ data });
                    }
                }
            });
        }
    }

    render() {
        const { data = {}, time } = this.state;
        const { dispatch, loading, modularName, active } = this.props;

        return (
            <div>
                <div className={styles.tool_wrapper}>
                    <div>
                        <MonthPicker
                            allowClear={false}
                            style={{ width: 220 }}
                            value={time}
                            onChange={this.onDateChange}
                        />
                    </div>
                    <div>
                        {/* <Radio.Group value={typeof time === 'object' ? time.format(CONST_PICKER_FORMAT) : time} onChange={this.onRadioChange}>
                            <Radio.Button value={moment().add(-1, 'months').format(CONST_PICKER_FORMAT)}>上个月</Radio.Button>
                            <Radio.Button value={moment().format(CONST_PICKER_FORMAT)}>当月</Radio.Button>
                            <Radio.Button value={moment().add(1, 'months').format(CONST_PICKER_FORMAT)}>下个月</Radio.Button>
                        </Radio.Group> */}
                        <ButtonGroup>
                            <Button onClick={this.onButtonClick.bind(this, 'prev')}>上个月</Button>
                            <Button onClick={this.onButtonClick.bind(this, 'current')} type={(typeof time === 'object' ? time.format(CONST_PICKER_FORMAT) : time) === moment().format(CONST_PICKER_FORMAT) ? 'primary' : ''}>当月</Button>
                            <Button onClick={this.onButtonClick.bind(this, 'next')}>下个月</Button>
                        </ButtonGroup>
                    </div>
                </div>
                <div className={styles.common_calendar_wrapper}>
                    {active === CONST_MODE_CALENDAR &&
                        <Spin spinning={!!loading.effects[`${modularName}/queryData`]}>
                            <Calendar
                                dateCellRender={(date) => {
                                    return <DateItem data={data[date.format(CONST_DATE_FORMAT)]} />
                                }}
                                headerRender={() => <div></div>}
                                // validRange={[moment(time).startOf('month'), moment(time).endOf('month')]}
                                value={time}
                                onSelect={this.onSelect}
                            />
                        </Spin>
                    }
                    {active === CONST_MODE_LIST &&
                        <List dispatch={dispatch} loading={loading} modularName={modularName} data={data} time={time} onSelect={this.props.onSelect} />
                    }
                </div>
            </div>
        );
    }
}

class DateItem extends Component {
    shouldComponentUpdate(nextProps, nextState) {
        return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState)
    }

    render() {
        const { data = {} } = this.props;

        return (
            <div>
                {data && Object.keys(data).map(id => {
                    const { shift_name, start_date, end_date, children = [] } = data[id];

                    return (
                        <div key={id} className={styles.date_item}>
                            <Tooltip placement='top' title={`${start_date}~${start_date < end_date ? `` : `次日`}${end_date}`}>
                                <div className={styles.shift_name}>{shift_name}</div>
                            </Tooltip>
                            <div className={styles.content}>
                                <Row>
                                    {children && children.length > 0 && children.map((child, index) => {
                                        return (
                                            <Tooltip
                                                key={index}
                                                placement='top'
                                                title={
                                                    <div>
                                                        <div>职位：{child.title_name}</div>
                                                        <div>电话号码：{child.mobile || '-'}</div>
                                                    </div>
                                                }
                                            >
                                                <Col span={24}>
                                                    {child.name}
                                                </Col>
                                            </Tooltip>
                                        );
                                    })}
                                </Row>
                            </div>
                        </div>
                    )
                })}
            </div>
        );
    }
}